package Schema::ResultSet::Transaction;

use Modern::Perl;
use base 'DBIx::Class::ResultSet';
use utf8;

sub by_acc_id {
    my ($self, $id) = @_;

    my $rs = $self->search(
        {
            -or => [
                debit_id  => $id,
                credit_id => $id,
            ],
        },
        {
            columns      => [
                'id',
                'debit_id',
                'd_sum',
                'credit_id',
                'c_sum',
                'time',
                'descr',
                { type => 'transaction_type.name' },
            ],
            join         => 'transaction_type',
            order_by     => 'time',
            result_class => 'DBIx::Class::ResultClass::HashRefInflator',
        },
    );

    my @result;

    while (my $row = $rs->next) {
        $row->{time} = localtime($row->{time});

        if ($id == $row->{credit_id} ) {
            $row->{acc_id} = $row->{debit_id};
            $row->{sum} = $row->{d_sum};
        }
        else {
            $row->{acc_id} = $row->{credit_id};
            $row->{sum} -= $row->{c_sum};
        }

        $row->{sum} = Schema::format_num($row->{sum});

        my $template = '<a href="/account/%d">%s</a>';
        $row->{descr} = sprintf $template, $row->{acc_id}, $row->{descr};

        $template = '<a href="/transaction/delete/%d">Удалить</a>';
        $row->{delete} = sprintf $template, $row->{id};

        push @result, [ @$row{ qw/ type time descr sum delete / } ];
    }

    return @result;
}

sub create {
    my ($self, $h) = @_;

    $h->{c_sum} =~ y/,/./;
    $h->{c_sum} =~ s/ //;
    $h->{c_sum} *= 100;
    $h->{d_sum} =~ y/,/./;
    $h->{d_sum} =~ s/ //;
    $h->{d_sum} *= 100;

    my $account = $self->result_source->schema->resultset('Account');

    my $debit_acc  = $account->find($h->{debit_id});
    $debit_acc->update({
        balance => $debit_acc->balance - $h->{d_sum},
    });

    my $credit_acc  = $account->find($h->{credit_id});
    $credit_acc->update({
        balance => $credit_acc->balance + $h->{c_sum},
    });

    return $self->next::method($h);
}

sub delete {
    my ($self, $id) = @_;

    my $transaction = $self->find($id);

    my $account = $self->result_source->schema->resultset('Account');

    my $debit_acc  = $account->find($transaction->debit_id);
    $debit_acc->update({
        balance => $debit_acc->balance + $transaction->d_sum,
    });

    my $credit_acc  = $account->find($transaction->credit_id);
    $credit_acc->update({
        balance => $credit_acc->balance - $transaction->c_sum,
    });

    return $self->next::method();
}

1;
